﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Typing_GUI
{
    public partial class frmGuestPlay : Form
    {
        public frmGuestPlay()
        {
            InitializeComponent();
        }

       #region "BIẾN"
       

        //Danh sach cac diem khoi dau cua cac phim ky tu
        Point[] InitPoints ={ new Point(13,72),new Point(72,109),new Point(81,145),new Point(101,182)};
        // diem khoi tao cao phim Shift ben trai
        Point ShiftLeftPoint = new Point(13, 182);
        //Diem khoi tao cua phim Shift ben phai
        Point ShiftRightPoint = new Point(490,182);
        //Diem khoi tao cua phim Space
        Point SpacePoint = new Point(177,220);
        //Diem khoi tao phim Caps Lock
        Point CapsLockPoint = new Point(13, 145);
        //Danh sách các bài tập theo cấp độ
        List<CLASS.CBaiTap> LessonList; 
        //Biến cho biết vị trí bài học
        int LessonCount = 0;
        //Danh sách các đoạn văn
        List<string> Paragraphs;
        //Biến đếm đoạn văn
        int ParagraphCount = 0;
        //Biến lưu 1 đoạn văn
        string Paragraph = "";
        //Bien luu  vi tri cua ki tu hien tai
        int count = 0;
        //Doi duong xu ly phan ban tay
        CLASS.CHands hand;
        //Bien luu gia tri dong va vi tri cua cac nut trong ban phim
        int line, pos;
        //Biến lưu số lỗi
        int errors = 0;bool isClicked = false;
        //Biến kiểm tra lỗi
        bool flag = true;
       
        //Thời gian
        int minutes = 0, second = 59; int time = 0;
        //Điểm đạt được
        int Score = 0;
     
        //Cấp độ bài tập
        public int levelLesson;
        //Danh sách cấp độ người dùng
        List<CLASS.CCapDoNguoiDung> userLevelList;
        #endregion
        #region "HÀM"
        //Hàm chống giật màn hình
         void AntiFlicker()
         {
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.DoubleBuffer, true);
         }
        //Hàm Play sound
       
        void PlaySound(string path)
        {

           // myAudio = new Audio(path);
           // myAudio.Play();
              
         byte[] result = System.IO.File.ReadAllBytes(path);
  
         System.IO.MemoryStream ms = new System.IO.MemoryStream(result);

            System.Media.SoundPlayer pl = new System.Media.SoundPlayer(ms);
           
            pl.Play();
           
        }
       
        void PlayTypeRightSound()
        {
            try
            {
                PlaySound("cached_type3.wav");
            }
            catch { }
           
        }
        void PlayTypeWrongSound()
        {
            try
            {
                PlaySound("cached_wrong.wav");
            }
            catch { }
        }
        //Hàm kiểm tra lỗi
        void SetError()
        {
            if (flag)
            {
                errors++;
                flag = false;
                lblErrors.Text = errors.ToString();
            }
            

        }
        //Hàm set avatar, level
       
        //Hàm lấy ra đoạn văn của bài tập
        List<string> GetParagraph(CLASS.CBaiTap lesson)
        {
            List<string> result = new List<string>();
           string []str=lesson.Noidung.Split(new string[]{"[P]"},StringSplitOptions.RemoveEmptyEntries);
           for (int i = 0; i < str.Length; i++)
               result.Add(str[i]);
            return result;
        }
        //Hàm hiển thị thời gian
        void SetTime()
        {
            
            lblTime.Text = (minutes - 1).ToString().PadLeft(2,'0') + ":" + second.ToString().PadLeft(2, '0');
            if (second == 0)
            {
                minutes = minutes - 1;
                second=59;
            }
        }
        //Ham khởi tạo giá trị ban đầu
        void InitLesson()
        {
            timer1.Enabled = false;
            Paragraphs = GetParagraph(LessonList[LessonCount]);
            ParagraphCount = 0;
            Paragraph = Paragraphs[ParagraphCount];
            rtxtContent.Text = Paragraph;
            rtxtContent.SelectAll();
            rtxtContent.SelectionColor = Color.Black;
            lblLessonName.Text = LessonList[LessonCount].Tenbaitap;
            rtxtDescription.Text = LessonList[LessonCount].Mota;
            minutes = LessonList[LessonCount].Thoigian;
            second = 59;
            Score = 0;
            errors = 0;
            lblErrors.Text = errors.ToString();
            lblScore.Text = Score.ToString();
            count = 0;
            time = 0;
          
        }
     

        //Hàm reset các nút 
        void ResetButtons()
        {
            if (LessonCount == 0)
            {
                btnNext.Enabled = true;
                btnPrev.Enabled = false;
            }
            else if (LessonCount == LessonList.Count - 1)
            {
                btnPrev.Enabled = true;
                btnNext.Enabled = false;
            }
            else
            {
                btnNext.Enabled = true;
                btnPrev.Enabled = true;
            }
            if (LessonList.Count == 1)
            {
                btnNext.Enabled = false;
                btnPrev.Enabled = false;
            }
        }
        #endregion

     
        private void frmGuestPlay_Load(object sender, EventArgs e)
        {


            levelLesson = 1; 

             AntiFlicker();
             hand = new Typing_GUI.CLASS.CHands();
           
             lblErrors.Text = errors.ToString();
             LessonList= CLASS.CBaiTap.GetLessonListByLevel(levelLesson, (int)CLASS.LessonTypes.Text);

             InitLesson();

           

             SetTime();

             ResetButtons();

             userLevelList = CLASS.CCapDoNguoiDung.GetUserLevels();

        }
       
        private void frmText_KeyPress(object sender, KeyPressEventArgs e)
        {
            timer1.Enabled = true;
            if (e.KeyChar == Paragraph[count])
            {
               
                flag = true;
                count++;
                rtxtContent.Select(0, count);
                rtxtContent.SelectionColor = Color.Blue;
                rtxtContent.SelectionFont = new Font(rtxtContent.Font, FontStyle.Regular);
                rtxtContent.Select(count, 1);
                rtxtContent.SelectionFont = new Font(rtxtContent.Font, FontStyle.Underline);
                
               PlayTypeRightSound();
                 Score = count / LessonList[LessonCount].CalculateScore();
            
            }
            else
            {
                if (!isClicked)
                {
                   
                    PlayTypeWrongSound();
                    isClicked = true;
                }
                SetError();
             
            }
            if (count == Paragraph.Length)
            {
                ParagraphCount++;
                if (ParagraphCount == Paragraphs.Count)
                {
                    int wpl = CLASS.CBaiTap.WordsInLesson(LessonList[LessonCount]);
                    timer1.Enabled = false;
                   
                    LessonCount++;
                    if (LessonCount >= LessonList.Count)
                    {

                        MessageBox.Show("Thanks for use the game!", "Message");
                        this.Close();
                        return;
                    }
                    else
                    {
                      
                        InitLesson();
                    }
                }
                else
                {
                    Paragraph = Paragraphs[ParagraphCount];
                    rtxtContent.Text = Paragraph;
                    rtxtContent.SelectAll();
                    rtxtContent.SelectionColor = Color.Black;
                    count = 0;
                }
            }
           
            
        }

        private void frmText_KeyUp(object sender, KeyEventArgs e)
        {

            isClicked = false ;
          
          
        }
             
        private void pbKeyboard_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                if (Paragraph[count] != ' ')
                {
                    CLASS.CKeyboard.DrawKey(InitPoints[line], 32, 30, e, Brushes.Blue, pos);
                    if (!CLASS.CKeyboard.CheckCapsLock())
                    {
                        if (char.IsUpper(Paragraph[count]))
                        {
                            if (pos > 4)
                                CLASS.CKeyboard.DrawKey(ShiftLeftPoint, 80, 30, e, Brushes.Blue, 0);
                            else
                                CLASS.CKeyboard.DrawKey(ShiftRightPoint, 80, 30, e, Brushes.Blue, 0);
                        }
                    }
                    else
                    {
                        CLASS.CKeyboard.DrawKey(CapsLockPoint, 61, 30, e, Brushes.Blue, 0);
                    }
                }
                else
                {
                    CLASS.CKeyboard.DrawKey(SpacePoint, 190, 36, e, Brushes.Blue, 0);
                }

            }
            catch { }
               
           
           
        }

        private void timer1_Tick(object sender, EventArgs e)
        {   
            second -= 1;
            
            lblScore.Text = Score.ToString();
            time++;
            if ((time / 60) >= LessonList[LessonCount].Thoigian)
            {
                timer1.Enabled = false;
                DialogResult result = MessageBox.Show("You are failed this lesson. Do you want to try it again?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if(result== DialogResult.No)
                {
                     LessonCount++;
                    if (LessonCount >= LessonList.Count)
                    {

                        levelLesson = levelLesson + 1;
                        LessonList = CLASS.CBaiTap.GetLessonListByLevel(levelLesson, 1);
                        LessonCount = 0;
                       
                        ResetButtons();
                        InitLesson();
                    }
                    else
                    {
                      
                        InitLesson();
                    }
                }
                else
                {
                    InitLesson();
                    //SetTime();
                }

            }
            SetTime();
        }

        private void pbHands_Paint(object sender, PaintEventArgs e)
        {
            CLASS.CHands.FindFinger(Paragraph[count], e);
        }

        private void btnBackToMenu_Click(object sender, EventArgs e)
        {
            
            this.Close();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            
                LessonCount += 1;
                if (LessonCount == LessonList.Count - 1)
                    btnNext.Enabled = false;
                btnPrev.Enabled = true;
                InitLesson();
                SetTime();
            
        }   

        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                CLASS.CKeyboard.GetKey(Paragraph[count], ref line, ref pos);
                pbKeyboard.Invalidate();
                pbHands.Invalidate();

                if (flag)
                {
                    pbWrong.Visible = false;
                }
                else
                {
                    pbWrong.Visible = true;
                }
            }
            catch { }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            LessonCount -= 1;
            if (LessonCount == 0)
                btnPrev.Enabled = false;
            btnNext.Enabled = true;
            InitLesson();
            SetTime();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void frmText_FormClosing(object sender, FormClosingEventArgs e)
        {
         
           
        }

        private void frmText_MouseLeave(object sender, EventArgs e)
        {
            
        }

        private void frmText_MouseEnter(object sender, EventArgs e)
        {
            
        }

     

       
    }
}